package com.dkd.easybook.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dkd.common.annotation.DataScope;
import com.dkd.common.core.domain.entity.SysUser;
import com.dkd.common.utils.EbUtils;
import com.dkd.easybook.domain.EbAccountCategoryDefault;
import com.dkd.easybook.domain.EbIcons;
import com.dkd.easybook.domain.EbUserAccountCategory;
import com.dkd.easybook.mapper.EbUserAccountCategoryMapper;
import com.dkd.easybook.service.IEbUserAccountCategoryService;
import com.dkd.easybook.tools.EbTools;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.dkd.common.enums.UpdateType;

import java.util.*;
/**
 * 用户记账类别Service业务层处理
 *
 * @author itheima
 * @date 2024-12-13
 */
@Service
public class EbUserAccountCategoryServiceImpl extends ServiceImpl<EbUserAccountCategoryMapper, EbUserAccountCategory> implements IEbUserAccountCategoryService {
    @Autowired
    private EbUserAccountCategoryMapper ebUserAccountCategoryMapper;
    @Autowired
    private EbAccountCategoryDefaultServiceImpl ebAccountCategoryDefaultServiceImpl;
    @Autowired
    private EbIconsServiceImpl ebIconsServiceImpl;
    //批量插入
    public int batchInsertEbUserAccountCategory(List<EbUserAccountCategory> ebUserAccountCategoryList) {
        return ebUserAccountCategoryMapper.batchInsertEbUserAccountCategory(ebUserAccountCategoryList);
    }
    /**
     * 查询用户记账类别
     *
     * @param userCategoryId 用户记账类别主键
     * @return 用户记账类别
     */
    @Override
    public EbUserAccountCategory selectEbUserAccountCategoryByUserCategoryId(Long userCategoryId) {
        return ebUserAccountCategoryMapper.selectEbUserAccountCategoryByUserCategoryId(userCategoryId);
    }
    /**
     * 查询用户记账类别列表
     *
     * @param ebUserAccountCategory 用户记账类别
     * @return 用户记账类别
     */
    @DataScope(deptAlias = "d", userAlias = "u")
    @Override
    public List<EbUserAccountCategory> selectEbUserAccountCategoryList(EbUserAccountCategory ebUserAccountCategory) {
        List<EbUserAccountCategory> ebUserAccountCategoryList = ebUserAccountCategoryMapper.selectEbUserAccountCategoryList(ebUserAccountCategory);
        for (EbUserAccountCategory _ebUserAccountCategory : ebUserAccountCategoryList) {
            if (_ebUserAccountCategory.getIconId() != null) {
                EbIcons ebIcons = ebIconsServiceImpl.getById(_ebUserAccountCategory.getIconId());
                if (ebIcons != null) {
                    String iconUrl = ebIcons.getUrl();
                    if (iconUrl != null) {
                        _ebUserAccountCategory.setIconUrl(iconUrl);
                    }
                }
            }
        }
        return ebUserAccountCategoryList;
    }
    /**
     * 新增用户记账类别
     *
     * @param ebUserAccountCategory 用户记账类别
     * @return 结果
     */
    @Override
    public int insertEbUserAccountCategory(EbUserAccountCategory ebUserAccountCategory) {
        EbUtils.setUserIdIfNull(ebUserAccountCategory,
                EbUserAccountCategory::getUserId,
                EbUserAccountCategory::setUserId);
        EbUtils.updateTableFields(UpdateType.ADD_FIELD,
                ebUserAccountCategory);
        return ebUserAccountCategoryMapper.insert(ebUserAccountCategory);
    }
    /**
     * 修改用户记账类别
     *
     * @param ebUserAccountCategory 用户记账类别
     * @return 结果
     */
    @Override
    public int updateEbUserAccountCategory(EbUserAccountCategory ebUserAccountCategory) {
        EbUtils.updateTableFields(UpdateType.UPDATE_FIELD,
                ebUserAccountCategory);
        Integer result = ebUserAccountCategoryMapper.updateById(ebUserAccountCategory);
        return result;
    }
    //批量修改用户记账类别
    @Override
    public int batchUpdateEbUserAccountCategory(List<EbUserAccountCategory> ebUserAccountCategoryList) {
        return ebUserAccountCategoryMapper.batchUpdateEbUserAccountCategory(ebUserAccountCategoryList);
    }
    /**
     * 批量删除用户记账类别
     *
     * @param userCategoryIds 需要删除的用户记账类别主键
     * @return 结果
     */
    @Override
    public int deleteEbUserAccountCategoryByUserCategoryIds(Long[] userCategoryIds) {
        return ebUserAccountCategoryMapper.deleteEbUserAccountCategoryByUserCategoryIds(userCategoryIds);
    }
    /**
     * 删除用户记账类别信息
     *
     * @param userCategoryId 用户记账类别主键
     * @return 结果
     */
    @Override
    public int deleteEbUserAccountCategoryByUserCategoryId(Long userCategoryId) {
        return ebUserAccountCategoryMapper.deleteEbUserAccountCategoryByUserCategoryId(userCategoryId);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchInsertEbUserAccountCategory(SysUser user) {
        // 获取 EbAccountCategoryDefault 表中的所有数据
        List<EbAccountCategoryDefault> defaultsCat = ebAccountCategoryDefaultServiceImpl.list();
        // 插入到 EbUserAccountCategory 表中，并创建一个映射，用于存储插入后的 EbUserAccountCategory 的 ID
        Map<Long, Long> idMapping = new HashMap<>();
        ArrayList<EbUserAccountCategory> userAccountCategoryList = new ArrayList<>();
        for (EbAccountCategoryDefault defaultCategory : defaultsCat) {
            EbUserAccountCategory userAccountCategory = new EbUserAccountCategory();
            userAccountCategory.setUserId(user.getUserId());
            BeanUtils.copyProperties(defaultCategory,
                    userAccountCategory,
                    "userId",
                    "create_time",
                    "update_time",
                    "create_by",
                    "update_by");
            EbUtils.updateTableFields(UpdateType.ADD_FIELD,
                    userAccountCategory);
            userAccountCategoryList.add(userAccountCategory);
        }
        this.saveBatch(userAccountCategoryList);
        List<EbUserAccountCategory> afterBatchEbUserAccountCategoryList = this.lambdaQuery()
                .eq(EbUserAccountCategory::getUserId,
                        user.getUserId())
                .list();
        for (EbAccountCategoryDefault defaultCategory : defaultsCat) {
            idMapping.put(defaultCategory.getCategoryId(),
                    afterBatchEbUserAccountCategoryList.get(defaultsCat.indexOf(defaultCategory))
                            .getUserCategoryId());
        }
        // 更新父子关系
        for (EbAccountCategoryDefault defaultCategory : defaultsCat) {
            Long defaultCategoryId = defaultCategory.getCategoryId();
            Long defaultParentIdFromDefault = defaultCategory.getParentId(); // 从默认表中获取父ID
            if (idMapping.containsKey(defaultCategoryId)) { // 确保该类别已被成功插入
                Long newUserCategoryId = idMapping.get(defaultCategoryId); // 新插入记录的ID
                // 使用映射找到新的父ID，如果不存在则使用0L表示无父节点
                Long newParentId = defaultParentIdFromDefault != null ? Optional.ofNullable(idMapping.get(defaultParentIdFromDefault))
                        .orElse(0L) : 0L;
                if (newParentId > 0 || newParentId.equals(0L)) { // 如果新父ID有效或为0（无父节点）
                    EbUserAccountCategory userAccountCategoryToUpdate = new EbUserAccountCategory();
                    userAccountCategoryToUpdate.setUserCategoryId(newUserCategoryId);
                    userAccountCategoryToUpdate.setParentId(newParentId);
                    this.update(userAccountCategoryToUpdate,
                            new LambdaQueryWrapper<EbUserAccountCategory>().eq(EbUserAccountCategory::getUserCategoryId,
                                    newUserCategoryId));
                }
            }
        }
        return idMapping.size(); // 返回成功插入并处理的记录数
    }
}
